package pres.liko.iot.gateway.filters;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName: BlackIpGlobalFilter
 * @Auther: liko
 * @Description: api黑名单
 * @Date: 2022/11/1 22:50
 */
@Component
public class UserGlobalFilter implements Ordered, GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取uri
        String uri = exchange.getRequest().getPath().toString();

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        System.out.println(antPathMatcher.match("/user/login/**", uri));

        if (antPathMatcher.match("/user/login/**", uri)) {
            return chain.filter(exchange);
        }
        if (!checkToken(exchange)) {
            return exchange.getResponse().writeAndFlushWith(
                    Mono.just(
                            Mono.just(
                                    DefaultDataBufferFactory
                                            .sharedInstance
                                            .allocateBuffer()
                                            .write("未登录".getBytes(StandardCharsets.UTF_8))
                            )
                    )
            );
        }

        return chain.filter(exchange);

        // return Mono.just(uri)
        //         // 不是登录的进行拦截
        //         .filter(s -> antPathMatcher.match("/user/login/**", uri))
        //         .map(s -> chain.filter(exchange))
        //         .defaultIfEmpty(
        //                 Mono.just(uri)
        //                         .filter(s -> checkToken(exchange))
        //                         .map(s -> chain.filter(exchange))
        //                         .defaultIfEmpty(
        //                                 exchange.getResponse().writeAndFlushWith(
        //                                         Mono.just(
        //                                                 Mono.just(
        //                                                         DefaultDataBufferFactory
        //                                                                 .sharedInstance
        //                                                                 .allocateBuffer()
        //                                                                 .write("未登录".getBytes(StandardCharsets.UTF_8))
        //                                                 )
        //                                         )
        //                                 )
        //                         )
        //                         .flatMap(voidMono -> voidMono);
        //         );

    }

    /**
     * 用户登录校验的优先级最高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }

    private boolean checkToken(ServerWebExchange exchange) {
        final ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (StringUtils.isBlank(token)) {
            return false;
        }
        // 自己的校验token逻辑
        Jwt parse = null;
        try {
            parse = Jwts.parser().setSigningKey("madedaodifanhuisha".getBytes(StandardCharsets.UTF_8)).parse(token);
        } catch (Exception e) {
            // e.printStackTrace();
            return false;
        }
        if (parse.getBody() == null) {
            return false;
        }
        return true;
    }
}
